import router, { constantRoutes, permRoutes } from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar stylee
import getPageTitle from '@/utils/get-page-title'
import store from './store'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()

  document.title = getPageTitle(to.meta.title)

  const token = store.getters.token
  // 有token,跳转的是首页(dashborad)
  if (token) {
    to.path === '/login' ? next('/') : next()

    if (!store.getters.userId) {
      await store.dispatch('user/saveUserInfoAction')

      const menus = store.state.user.userInfo.roles.menus
      console.log(menus)

      const newRoutes = permRoutes.filter(item => {
        return menus.includes(item.name)
      })

      store.commit('user/saveRoutes', [...constantRoutes, ...newRoutes])
      // 添加路由
      router.addRoutes([...newRoutes, { path: '*', redirect: '/404', hidden: true }])
    }
    NProgress.done()
    return
  }

  // 没有token,去白名单
  if (whiteList.includes(to.path)) {
    next()
    NProgress.done()
    return
  } else {
    next('/login')
    Message.info('请先登录')
    NProgress.done()
    return
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
